import router from './router'
import store from './store/'
import storage from 'store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import {
  setDocumentTitle,
  domTitle
} from '@/utils/domUtil'
import {
  ACCESS_TOKEN,
  APP_USER,
  APP_DEPT,
  AUTHORIZATION
} from '@/store/mutation-types'
import {
  i18nRender
} from '@/locales'
import {
  checkLogin,
  getMyInfo,
  getSsoAuthUrl
} from '@/api/sso'
import {
  getUrlParameter
} from '@/utils/util.js'

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration
const defaultPath = 'sfapprove-web' // 默认项目名

// 路由白名单
const whiteList = ['login', '404', '/gzt_approval_form']

// 主页
const indexRoutePath = '/login'
const notfoundPath = '/404'

router.beforeEach(async (to, from, next) => {
  NProgress.start() // start progress bar
  to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`)
  if (to.path.indexOf(indexRoutePath) >= 0 && to.fullPath.indexOf(notfoundPath) >= 0) {
    // 清理路由
    store.dispatch('cleanRouters').then(() => { })
    next()
    NProgress.done()
  } else {
    if (storage.get(ACCESS_TOKEN)) {
      // 验证是否已登录系统
      const sres = await checkLogin()
      // 未登录系统
      if (!sres.data) {
        const cres = await getSsoAuthUrl({
          back: location.href.substring(0, location.href.indexOf(defaultPath) + defaultPath.length) + '/ssoback'
        })
        // console.log('111', cres)
        // 
        // 清除登录信息
        localStorage.removeItem(ACCESS_TOKEN)
        localStorage.removeItem(APP_USER)
        localStorage.removeItem(APP_DEPT)
        window.location.href = cres.data
      }
      // 加载动态枚举
      store.dispatch('GetEnumList')
      store.dispatch('GetEnumValuesList')
      // 默认设置白色主题
      store.dispatch('ToggleTheme', 'light')
      if (store.getters.addRouters.length === 0) {
        const token = {
          token: storage.get(ACCESS_TOKEN)
        }
        store.dispatch('GenerateRoutes', token).then(() => {
          // 动态添加可访问路由表
          router.addRoutes(store.getters.addRouters)
          const redirect = decodeURIComponent(from.query.redirect || to.path)
          if (to.path === redirect) {
            next({
              ...to,
              replace: true
            })
          } else {
            // 跳转到目的路由
            next({
              path: redirect
            })
          }
        })
      } else {
        next()
      }
    } else {
      if (window.location.href.indexOf(AUTHORIZATION) > -1) {
        const satoken = getUrlParameter(window.location.href, AUTHORIZATION)
        storage.set(ACCESS_TOKEN, satoken)
        const ures = await getMyInfo()
        // 存储用户信息
        if (ures.data) {
          storage.set(APP_USER, ures.data)
          if (ures.data.deptlist == null) {
            console.error('登录人部门信息为空')
          }
          storage.set(APP_DEPT, ures.data.deptlist[0] || {})
        } else {
          const cres = await getSsoAuthUrl({
            back: location.href.substring(0, location.href.indexOf(defaultPath) + defaultPath.length) + '/ssoback'
          })
          // console.log('222', cres)
          // 
          window.location.href = cres.data
        }
        next({
          path: '/home'
        })
      } else if (whiteList.includes(to.path)) {
        // 在免登录白名单，直接进入
        next()
      } else {
        const cres = await getSsoAuthUrl({
          back: location.href.substring(0, location.href.indexOf(defaultPath) + defaultPath.length) + '/ssoback'
        })
        window.location.href = cres.data
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})